import React from 'react';

// import defImg from '../assets/img/default.jpg'
import './Cart.scss'
import cart0 from "../../mock/cart.json"
import CartItem from './CartItem';

import { useState, useEffect, useCallback } from 'react';

const Cart = () => {

    const [cart, setCart] = useState<Item[]>([])
    const [allSelected, setAllSelected] = useState(false)

    /* 添加单品 */
    const addItem = useCallback(
        (i:number) => {
            console.log("addItem", i);
            setCart(cart.map(
                (item, _i) => {
                    _i === i && item.count++
                    return item
                }
            ))
        },
        [cart],
    )

    /* 减少单品 */
    const subItem = useCallback(
        (i:number) => {
            console.log("subItem", i);
            setCart(cart.map(
                (item, _i) => {
                    (_i === i && item.count) && item.count--
                    return item
                }
            ))
        },
        [cart],
    )

    /* 移除单品 */
    const removeItem = useCallback(
        (i:number) => {
            console.log("removeItem", i);
            setCart(cart.filter((item, _i) => _i !== i))
        },
        [cart],
    )

    /* 消选单品 */
    const toggleItem = useCallback(
        (i:number) => {
            console.log("toggleItem", i);
            console.log("cart", cart);

            const item = cart.find(
                (item, _i) => {
                    console.log("_i", _i);
                    return _i === i
                }
            )

            if (item) {
                console.log("here");
                item.selected = !item.selected
                setCart([...cart])
            }
        },
        [cart],
    )

    /* 计算总数量 */
    const getTotalCount = useCallback(
        () => {
            // console.log("getTotalItems");
            return cart.filter(
                item => item.selected
            ).reduce(
                (pv, cv, i) => {
                    // console.log(pv, cv);
                    return pv + cv.count
                },
                0
            )
        },
        [cart],
    )

    /* 计算总金额 */
    const getTotalAmount = useCallback(
        () => {
            // console.log("getTotalAmount");
            return cart.filter(
                item => item.selected
            ).reduce(
                (pv, cv, i) => {
                    // console.log(pv, cv);
                    return pv + cv.price * cv.count
                },
                0
            )
        },
        [cart],
    )

    /* 
    模拟组件挂载生命周期
    组件首次挂载时获取用户数据
    */
    useEffect(() => {
        console.log("ComponentDidMount");
        !cart.length && setCart(cart0)

        /* 组件卸载时可以清理一下数据，避免内存泄漏 */
        return ()=>{
            console.log("ComponentWillUnmount");
            setCart([])
        }
    }, [])

    /* ===== 全选的"双向数据绑定" ===== */
    /* 
    侦听购物车数据变化，以切换全选状态
    cart驱动allSelected
    */
    useEffect(() => {
        // console.log("useEffect", "cart=>allSelected");
        cart.every(item => item.selected)
            ? setAllSelected(true)
            : setAllSelected(false)
        // return () => { }
    }, [cart])

    /* allSelected不宜再直接驱动cart 会陷入死锁 */
    // useEffect(() => {
    //     cart.forEach(item => item.selected = allSelected)
    //     setCart([...cart])
    // }, [allSelected])

    /*     
    用户主动使用【全选】功能时
    先修改cart数据（全选或全消）然后由cart驱动allSelected 
    */
    const toggleAllSelected = useCallback(
        (value:boolean) => {
            console.log("toggleAllSelected", value);
            // setAllSelected(value)

            // 先修改cart数据为（全选或全消）
            // 修改购物车数据=>【数据侦听逻辑A】会触发setAllSelected
            cart.forEach(item => item.selected = value)
            setCart([...cart])
        },
        [cart],
    )
    /* ===== ENDOF 全选的"双向数据绑定" ===== */

    /* 函数式组件=>渲染JSX */
    return (
        <div className="cart-wrapper">

            <div className="top">
                <div className='sel-box'>
                    <input type="checkbox"
                        checked={allSelected}
                        onChange={
                            (e) => {
                                console.log("全选input onChanged", !allSelected);
                                toggleAllSelected(!allSelected)
                            }
                        } />
                    <i>全选</i>
                </div>

                <span className='imgname-box'>商品名称</span>
                <span>单价</span>
                <span className='count-box'>数量</span>
                <span>金额</span>
                <span>操作</span>
            </div>

            <div className="middle">
                <ul>{
                    cart.map(
                        (item, i) =>
                            <CartItem
                                index={i}
                                item={item}
                                addItem={addItem}
                                subItem={subItem}
                                removeItem={removeItem}
                                toggleSelection={toggleItem}
                                key={item.name}
                                >
                            </CartItem>
                    )
                }</ul>
            </div>

            <div className="bottom">
                <div className="left"></div>
                <div className='count-box'>
                    已选商品 <span className='price'>{getTotalCount()}</span> 件
                </div>
                <div className='amount-box'>
                    总计 <span className='price'>{getTotalAmount().toFixed(2)}</span>
                </div>
                <div className="pay-box">
                    <i>结 算</i>
                </div>
            </div>

        </div>
    );
}

export default Cart;
